/**
 * This code is originally written by Lars Vogel
 * http://www.vogella.de/articles/AndroidListView/article.html
 * and modified by me.
 *
 * @author prebz
 */

package com.wirelesstransfer.activity.status;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.wirelesstransfer.R;
import com.wirelesstransfer.connection.ITransferData;

import android.app.Activity;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class CustomClientArrayAdapter extends ArrayAdapter<File> {

	private final Activity context;
	private final List<File> files;
	private List<String> status;
	private ITransferData data;
	private Resources res;

	
	/**
	 * 
	 * @param context from activity which will create the adapter
	 * @param names of all the files
	 * @param allFilesSize the size of all the files
	 * @param data 
	 */
	public CustomClientArrayAdapter(Activity context, List<File> files, ITransferData data) {
		super(context, R.layout.rowclients, files);
		this.context = context;
		this.files = files;
		this.data = data;
		
		res = context.getResources();
	}
	
	// saves the reference of the object in list
	static class ViewHolder {
		public TextView textViewFiles;
		public TextView textViewFileStatus;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		ViewHolder holder;

		// reuse existing views for performance
		View rowView = convertView;
		if (rowView == null) {
			LayoutInflater inflater = context.getLayoutInflater();
			rowView = inflater.inflate(R.layout.rowclients, null, true);
			holder = new ViewHolder();
			holder.textViewFiles = (TextView) rowView.findViewById(R.id.fileclient_txt);
			holder.textViewFileStatus = (TextView) rowView.findViewById(R.id.fileclientstatus_txt);
			rowView.setTag(holder);
		} else {
			holder = (ViewHolder) rowView.getTag();
		}

		status = setFileStatus(data);
		
		holder.textViewFiles.setText(files.get(position).getName());
		holder.textViewFileStatus.setText(status.get(position).toString());

		return rowView;
	}
	
	private List<String> setFileStatus(ITransferData files){
		List<String> status = new ArrayList<String>();
		
		int done;		
		if(files.getReceivedFiles() == null){
			done = 0;
		}
		else
			done  = files.getReceivedFiles().size(); 

		int remaning;
		if(files.getRemainingFiles() == null){
			remaning = 0;
		}
		else
			remaning  = files.getRemainingFiles().size(); 
		
		for(int i = 0; i < done; i++){
			status.add(res.getString(R.string.fileclient_status_done));
		}
		
		status.add(res.getString(R.string.fileclient_status_downloading));
		
		for(int i = 0; i < remaning; i++){
			status.add(res.getString(R.string.fileclient_status_waiting));
		}
		
		return status;
	}
	
}
